import { Component, OnInit, Input, Output, forwardRef, EventEmitter, } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';
import { CommonService } from '../../../services-common/common.service';

@Component({
  selector: 'app-upload-files',
  templateUrl: './upload-files.component.html',
  styleUrls: ['./upload-files.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => UploadFilesComponent),
      multi: true
    }
  ]
})
export class UploadFilesComponent implements ControlValueAccessor, OnInit {

  @Input() uploadBtnText: string = 'Upload';
  @Input() isArrayType: boolean = true;
  @Input() disabled: boolean = false;
  @Input() uploadFileName: string = 'storeUploadFile';
  @Input() limitSize: number = 5;

  @Output() fileChange: any = new EventEmitter();

  uploadLoading: boolean = false;
  fileList: Array<any> = [];
  onChange: any = () => {};

  constructor(
    private msg: NzMessageService,
    private commonService: CommonService
  ) { }

  ngOnInit(): void {
  }

  handleList(arrs: Array<string>) {
    let newArr: Array<any> = [];
    if (arrs) {
      newArr = arrs.map(m => {
        let nArr = m.split('/');
        return {
          name: nArr[nArr.length - 1],
          url: m
        }
      })
    }

    return newArr;
  }

  writeValue(val: any) {
    let valType = Object.prototype.toString.call(val);
    this.fileList = (this.isArrayType && valType === '[object Array]') ?
                    this.handleList(val) :
                    ((valType === '[object String]' && val) ? this.handleList(val.split(',')) : []);
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    // this.onTouched = fn;
  }

  handleChange(ev: any) {
    const { originFileObj }: any = ev?.file;
    this.uploadInterface(originFileObj);
  }

  /**
   * @description: Upload Interface
   * @param {File} file
   * @return
   */  
  async uploadInterface(file: File) {
    if (!file || this.uploadLoading) {
      return
    }

    let jqIndex = file.name.lastIndexOf('.');
    let fileName = !this.commonService.isEmpty(file.name) ? file.name.substring(0, jqIndex) : '文件名';

    this.uploadLoading = true;
    const res: any = await this.commonService.uploadFileData(file, this.uploadFileName, fileName);
    this.uploadLoading = false;
    if (res.code == 0) {
      this.msg.success('文件上传成功');

      this.fileList.push({
        name: fileName,
        url: res.data
      });

      let tempVal = this.isArrayType ? this.fileList.map(m => m.url) : this.fileList.map(m => m.url).join(',');
      this.onChange(tempVal);
      this.fileChange.emit(tempVal);
    } else {
      this.msg.error(res.message);
    }
  }

  deleteFile(index: number) {
    this.fileList.splice(index, 1);
    
    let tempVal = this.isArrayType ? this.fileList.map(m => m.url) : this.fileList.map(m => m.url).join(',');
    this.onChange(tempVal);
    this.fileChange.emit(tempVal);
  }

  downFileData(item: any) {
    this.commonService.downLoadUrlFile(item.url);
  }
}
